
--[排序遍历]
function sortpairs(self)
    local mt
    local func
    local sort = {}
    for k, v in pairs(self) do
        sort[#sort+1] = {k, v}
    end
    table.sort(sort, function (a, b)
        return a[1] < b[1]
    end)
    local n = 1
    return function()
        local v = sort[n]
        if not v then
            return
        end
        n = n + 1
        return v[1], v[2]
    end
end



local table_remove = table.remove

function table.remove(t, p)
	if p and type(p) ~= 'number' then
		for i = 1, #t do
			local v = t[i]
			if v == p then
				return table_remove(t, i)
			end
		end
	else
		return table_remove(t, p)
	end
end

-- 浅拷贝
function table.copy(t)
	local nt = {}
	for k, v in pairs(t) do
		nt[k] = v
	end
	return nt
end

-- 复制表（深拷贝）
function table.deepcopy(object)
	local lookup_table = {}
	local function _copy(object)
		if type(object) ~= "table" then
		 return object
		elseif lookup_table[object] then
		 return lookup_table[object]
		end
		local new_table = {}
		lookup_table[object] = new_table
	for index, value in pairs(object) do
		new_table[_copy(index)] = _copy(value)
	end
	return setmetatable(new_table, getmetatable(object))
	end
	return _copy(object)
end


-- 取一个随机元素
function table.random(t)
	local count = #t
	if count > 0 then
		local index = math.random(1, count)
		return t[index], index
	end
end

-- 取出数个不重复的随机元素
function table.random_table(tab, number)
	local random_table = {}
	if #tab < number then
		return tab
	end
	local tbl = table.copy(tab)
	while #random_table < number do
		local random_element, index = table.random(tbl)
		table.insert(random_table, random_element)
		table.remove(tbl, index)
	end
	return random_table
end

-- 根据表里的概率取出指定索引
function table.random_table_index(tab) 
	local rand = math.random(10000) / 100 
	local num = 0
	for index, rate in ipairs(tab) do 
		num = num + rate 
		if rand <= num then 
			return index
		end 
	end 
	return 1 
end 

-- 根据权重取出一个随机元素
-- tab：{{value, pr}, {value, pr}, {value, pr}}
function table.get_by_weight(tab)
	local obj
	if not tab or #tab == 0 then
		return obj
	end

	local pr_total = 0
	for _, v in ipairs(tab) do
		pr_total = pr_total + v[2]
	end

	if pr_total <= 0 then
		return obj
	end

	local random_num = math.random(1, pr_total)
	local pr_hit = 0
	local index = 0
	for i, v in ipairs(tab) do
		if pr_hit <= random_num and random_num <= pr_hit + v[2] then
			index = i
			obj = v[1]
			break
		end
		pr_hit = pr_hit + v[2]
	end

	return obj, index
end

-- 找到表中某个元素的索引
function table.find(t, value)
	for i = 1, #t do
		if t[i] == value then
			return i
		end
	end
end

-- 检查表是否为空
function table.is_empty(t)
	for _, _ in pairs(t) do 
		return false 
	end
    return true
end


--将多个表合并成一个
function table.list_merge(...)
	local result = {}

	local arg_list = {...}
	local arg_count = select('#', ...)

	for _, arg in ipairs(arg_list) do 
		for i, v in ipairs(arg) do 
			result[#result + 1] = v 
		end 
	end 
	return result
end 